package com.halflife.comeElectricity.admin;

import com.halflife.comeElectricity.admin.service.AdminService;
import com.halflife.framework.participant.range.RangeInfo;
import com.halflife.framework.participant.range.RangeInfoRepository;
import com.halflife.framework.participant.range.RoleMembership;
import com.halflife.framework.participant.range.RoleMembershipRepository;
import com.halflife.framework.participant.range.util.Menu;
import com.halflife.framework.participant.range.util.RangeUtil;
import com.halflife.framework.participant.user.UserView;
import com.halflife.framework.participant.user.UserViewRepository;
import com.halflife.shiro.utils.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by zhaoyf on 2018/2/24.
 */
@Controller
public class AdminController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @RequestMapping("/admin/index")
    public String index(HttpServletResponse response, HttpServletRequest request, ModelAndView mv) {
        return "index";
    }

    @RequestMapping(value = "/admin/login", method = {RequestMethod.GET})
    public String login(HttpServletResponse response, HttpServletRequest request, ModelAndView mv) {
        return "login";
    }

    @RequestMapping("/")
    public String home() {
        return "redirect:/admin/login";
    }

    @RequestMapping("/yy")
    public String yy() {
        return "index";
    }


//    @RequestMapping(value = "/admin/login", method = {RequestMethod.POST})
//    public String logins(String username, String password, HttpServletResponse response, HttpServletRequest request, Model model) {
//        if ("admin".equals(username) && "password".equals(password)) {
//            UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
//            SecurityUtils.getSubject().login(token);
////            ShiroUtil.setUser(new com.halflife.comeElectricity.user.User(1, "18681240568", "1111", "111", true));
//            //SecurityUtils.getSubject().getSession().setAttribute();
//            return "index";
//        }
//        model.addAttribute("message", "用户名密码错误");
//        return "login";
//    }
    @Resource
    AdminService adminService;
    @Resource
    UserViewRepository userViewRepository;
    @Resource
    RoleMembershipRepository roleMembershipRepository;
    @Resource
    RangeInfoRepository rangeInfoRepository;
    @RequestMapping(value = "/admin/login", method = {RequestMethod.POST})
    public String logins(String username, String password, Integer type,
                         HttpServletResponse response, HttpServletRequest request, Model model) {

        UserView user = new UserView();
        try{

            if(username!=null && password!=null){

                user = adminService.validUserPassword(username, password, type);
            }
            if (user!=null && user.getValidMessage()==null) {
                //验证通过
                UsernamePasswordToken token = new UsernamePasswordToken(username, password, true);
                //获取角色列表
                Map<String, Object> queryMap = new HashMap<String, Object>();
                queryMap.put("valid", true);
                queryMap.put("userViewId", user.getId());
                List<RoleMembership> roleList = roleMembershipRepository.selectAll(queryMap);
                //获取角色Map/Ids
                List<String> roleIds = new ArrayList<String>();
                //获取用户权限
                queryMap.clear();
                StringBuffer endSqlStr = new StringBuffer();
                endSqlStr.append(" t.rangeInfoId is not null");
                endSqlStr.append(" and ( t.rangeState = 1 or ( exists (");
                endSqlStr.append(" select rr.id from t_rolerange rr ");
                endSqlStr.append(" where t.id = rr.rangeInfoId ");
                endSqlStr.append(" and exists(select rf.id from t_rangeinfo rf where rr.rangeInfoId = rf.id and rf.rangeState = 0) ");
                endSqlStr.append(" and exists(select rm.id from t_rolemembership rm where rm.roleId = rr.roleId and rm.userViewId = "+ user.getId() +"))))");
                //推送查询条件
                queryMap.put("valid", true);
                queryMap.put("endSql", endSqlStr.toString());
                queryMap.put("orderSql", "t.ordinal, t.id");
                List<RangeInfo> rangeList = rangeInfoRepository.selectAll(queryMap);
                //根据权限生成菜单
                List<Menu> menus = RangeUtil.getMenuRangeList(rangeList);

                SecurityUtils.getSubject().getSession().setAttribute("roleMap", RangeUtil.getRoleMap(roleList, roleIds));
                SecurityUtils.getSubject().getSession().setAttribute("roleIds", roleIds);
                SecurityUtils.getSubject().getSession().setAttribute("menus", menus);
                SecurityUtils.getSubject().getSession().setAttribute("user", user);
                SecurityUtils.getSubject().login(token);

                //推送用户
                ShiroUtil.setUserview(user);
                SecurityUtils.getSubject().getSession().setAttribute("userId", adminService.getUserIdByType(type, user.getId()));
//                return "index";
//                return adminService.getIndexUrlByType(type);
                UserView logUser = new UserView();
                logUser.setId(user.getId());
                logUser.setLastLoginTime(new Date());
                logUser.setLoginCount(user.getLoginCount()==null?0:(user.getLoginCount()+1));
                userViewRepository.updateByPrimaryKeySelective(logUser);
                return "redirect:/admin/parameters/index";
            }
        }catch (Exception e){

            e.printStackTrace();
            log.info(e.getMessage());
        }
        //推送错误信息
        model.addAttribute("message", user.getValidMessage());
        return adminService.getUrlByType(type);
    }
}
